//
//  DownLoadViewController.m
//  StudyDemo
//
//  Created by 赵忠鹏 on 2018/5/4.
//  Copyright © 2018年 zhaozhongpeng. All rights reserved.
//

#import "DownLoadSmallFileViewController.h"
#import <AVKit/AVKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface DownLoadSmallFileViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIButton *playerButton;

@property (weak, nonatomic) IBOutlet UIProgressView *downLoadProgess;

@property (nonatomic,strong) NSMutableData *fileData;

@property (nonatomic,assign) CGFloat totalLength;

@property (nonatomic,copy) NSString *fileName;

#pragma mark NSData

@property (weak, nonatomic) IBOutlet UIImageView *NSDataImageView;

#pragma mark connection-Asyn

@property (weak, nonatomic) IBOutlet UIImageView *ConnectionAsynImageView;
@end

@implementation DownLoadSmallFileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (IBAction)NSDataButtonClick:(id)sender {
    NSURL *NSDataUrl = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"];
    NSData *data = [NSData dataWithContentsOfURL:NSDataUrl];
    self.NSDataImageView.image = [UIImage imageWithData:data];
}

- (IBAction)ConnectionasynButtonClick:(id)sender {
    NSURL *ConnectionasynUrl = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
    NSURLRequest *ConnectionasynRequest = [[NSURLRequest alloc] initWithURL:ConnectionasynUrl];
    
    [NSURLConnection sendAsynchronousRequest:ConnectionasynRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        self.ConnectionAsynImageView.image = [UIImage imageWithData:data];
    }];
    
}

- (IBAction)backClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 开始下载
- (IBAction)staterDownButtonClick:(id)sender {
    
    NSString *resource = @"http://120.25.226.186:32812/resources/videos/minion_01.mp4";
    
    NSURL *url = [NSURL URLWithString:resource];
    
    NSURLRequest *resourceRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection connectionWithRequest:resourceRequest delegate:self];
    
}

//: 将要发送请求时调用、
//: 是在需要改变request（重定向）的时候，返回一个request来进行继续加载，当然也可以返回nil（connection就会被终止，  delegate回调会继续直到finish／error，一般情况下是error）
- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response{
    
    NSString *resource = @"http://120.25.226.186:32812/resources/videos/minion_01.mp4";
    
    NSURL *url = [NSURL URLWithString:resource];
    
    if ([request.URL isEqual:url]) {
        NSLog(@"I Am Comming - %@",request.URL);
    }
    
    return request;
}

//: 开始接收到服务器的响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.fileData = [NSMutableData data];
    
    self.totalLength = response.expectedContentLength;
    NSLog(@"totalLength - %f",self.totalLength);
    
    self.fileName = response.suggestedFilename;
    
}

//: 接收到服务器返回的数据时调用（服务器返回的数据比较大时会调用多次,一般做大文件下载）
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.fileData appendData:data];
    
    self.downLoadProgess.progress = 1.0 * (self.fileData.length/self.totalLength);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    NSString *pathStr = [NSString stringWithFormat:@"/Users/zhaozhongpeng/Desktop/StudycCaches/%@",self.fileName];
    [self.fileData writeToFile:pathStr atomically:YES];
    
    
    MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathStr]];
    [self.navigationController presentViewController:playerVC animated:YES completion:nil];
    
}


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"跪了 - %@",error);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
